# coding: utf-8
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QVBoxLayout, QWidget
from qeventmanager import qevent_manager

from common.server import BananaServer
from components import CustomScrollArea
from ..home_interface import ClassicHeaderCardWidget
from ..tools import check_result


class ClassListInterface(CustomScrollArea):
    moreSignal = Signal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget()
        self.verticalLayout = QVBoxLayout(self.view)

        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName("ClassListInterface")
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(20)
        self.setWidget(self.view)

    def load(self):
        qevent_manager.addTask(BananaServer.listing, self.currentPage, slot=self.on_load_listing)

    def on_load_listing(self, result: dict):
        data = check_result(result)
        if data is None:
            return
        rows = data.get('rows', [])
        self.totalPages = data['pageinfo']['totalpage']
        for row in rows:
            card = ClassicHeaderCardWidget(row['spname'], self)
            card.setContent(row['intro'])
            card.load(row.get('vodrows', []))
            card.setMoreButtonVisible(True)
            card.setProperty('spid', row['spid'])
            card.moreSignal.connect(self.moreSignal)
            self.verticalLayout.addWidget(card, 0, Qt.AlignmentFlag.AlignTop)

    def nextPage(self):
        super().nextPage()
        self.load()
